<?php
namespace plugin\ky_shouyin\app\controller;

use support\Request;
use support\Db;

class StatisticsController extends BaseController
{
    public function index()
    {
        return $this->view('statistics/index');
    }
    
    /**
     * 获取销售统计数据
     */
    public function getSalesData(Request $request)
    {
        $startDate = $request->get('start_date', date('Y-m-d'));
        $endDate = $request->get('end_date', date('Y-m-d'));
        $storeId = $request->get('store_id');
        
        try {
            $query = Db::table('ky_order')
                ->where('status', 1) // 已完成
                ->whereBetween('created_at', [$startDate.' 00:00:00', $endDate.' 23:59:59']);
                
            if ($storeId) {
                $query->where('store_id', $storeId);
            }
            
            // 订单总数和金额
            $orderStats = $query->selectRaw('COUNT(*) as order_count, SUM(amount) as total_amount')->first();
            
            // 商品销量排行
            $goodsRanking = Db::table('ky_order_goods')
                ->leftJoin('ky_order', 'ky_order_goods.order_id', '=', 'ky_order.id')
                ->leftJoin('ky_goods', 'ky_order_goods.goods_id', '=', 'ky_goods.id')
                ->where('ky_order.status', 1)
                ->whereBetween('ky_order.created_at', [$startDate.' 00:00:00', $endDate.' 23:59:59'])
                ->when($storeId, function($query) use ($storeId) {
                    return $query->where('ky_order.store_id', $storeId);
                })
                ->groupBy('ky_order_goods.goods_id')
                ->selectRaw('ky_goods.name, SUM(ky_order_goods.quantity) as total_quantity, SUM(ky_order_goods.amount) as total_amount')
                ->orderByDesc('total_quantity')
                ->limit(10)
                ->get();
            
            // 每日销售趋势
            $dailySales = Db::table('ky_order')
                ->where('status', 1)
                ->whereBetween('created_at', [$startDate.' 00:00:00', $endDate.' 23:59:59'])
                ->when($storeId, function($query) use ($storeId) {
                    return $query->where('store_id', $storeId);
                })
                ->selectRaw('DATE(created_at) as date, COUNT(*) as order_count, SUM(amount) as total_amount')
                ->groupBy('date')
                ->get();
            
            return json([
                'code' => 0,
                'msg' => 'success',
                'data' => [
                    'order_stats' => $orderStats,
                    'goods_ranking' => $goodsRanking,
                    'daily_sales' => $dailySales
                ]
            ]);
        } catch (\Exception $e) {
            return json(['code' => 1, 'msg' => '获取数据失败：' . $e->getMessage()]);
        }
    }
} 